﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using Common.Utilities;
using Common.Utilities.Dispatcher;

namespace Workflows.Components.ETL
{
    /// <summary>
    /// 
    /// </summary>
    public class TablePartitionWorker:IWorker 
    {
        #region Implementation of IWorker

        public event WorkerStarted WorkerStartedEvent;
        public event WorkerFinished WorkerFinishedEvent;
        public event WorkerHasError WorkerErredEvent;
        public event WorkerCancelled WorkerCancelledEvent;
        public event WorkerStatusChanged WorkerStatusChangedEvent;

        private Thread workerThread;
        private TablePartitionInstruction instruction;
        private TablePartitionOutput output;
        private RunContext _Context;
        private Guid _TicketID;
        private string _WorkflowName;
        private string _ComponentName;

        /// <summary>
        /// 
        /// </summary>
        public string ComponentName
        {
            get { return _ComponentName; }
        }

        /// <summary>
        /// 
        /// </summary>
        public string WorkflowName
        {
            get { return _WorkflowName; }
        }

        /// <summary></summary>
        public Thread WorkerThread
        {
            get { return workerThread; }
        }
        /// <summary></summary>
        public InstructionBase Instruction
        {
            get { return instruction; }
        }
        /// <summary></summary>
        public ResultBase Output
        {
            get { return output; }
        }
        /// <summary></summary>
        public Type ComponentType
        {
            get { return typeof(TablePartitionComponent); }
        }
        /// <summary></summary>
        public RunContext Context
        {
            get { return _Context; }
            set { _Context = value; }
        }
        /// <summary></summary>
        public void SetInstruction(Guid ticketGuid, InstructionBase request, string workflowName, string componentName)
        {
            this._TicketID = ticketGuid;
            this.instruction = (TablePartitionInstruction)request;
            this._WorkflowName = workflowName;
            this._ComponentName = componentName;
        }
        /// <summary></summary>
        public void SetInstruction(RunContext context, Guid ticketGuid, InstructionBase request, string workflowName, string componentName)
        {
            this._TicketID = ticketGuid;
            this.instruction = (TablePartitionInstruction)request;
            this._Context = context;
            this._WorkflowName = workflowName;
            this._ComponentName = componentName;
        }
        /// <summary></summary>
        public void DoWork()
        {
            if (this.WorkerStartedEvent != null)
            {
                this.WorkerStartedEvent(this._TicketID, this, this.GetType(), this.instruction);
            }
            this.workerThread = Thread.CurrentThread;
            this.PartitionTable();
        }
        /// <summary></summary>
        public void DoWorkAsync()
        {
            if (this.WorkerStartedEvent != null)
            {
                this.WorkerStartedEvent(this._TicketID, this, this.GetType(), this.instruction);
            }
            this.workerThread = new Thread(new ThreadStart(this.PartitionTable));
            this.workerThread.Start();
        }
        /// <summary></summary>
        public void CancelWork()
        {
            if (this.workerThread != null && this.workerThread.IsAlive)
            {
                this.workerThread.Abort();
                this.workerThread.Join();

                if (this.WorkerCancelledEvent != null)
                {
                    this.WorkerCancelledEvent(this._TicketID, this.GetType(), this.instruction);
                }
            }
        }

        #endregion

        #region work
        private void PartitionTable()
        {
            try
            {
                int totalParts = DbUtil.PartitionTableOnFields(
                    this.instruction.ConnStr, this.instruction.SchemaName,
                    this.instruction.TblName, this.instruction.PartitionFields,
                    this.instruction.RecordPerTable, this.instruction.OutputTablePrefix);
                //if (this.instruction.GroupByFieldValue)
                //{
                //    DbUtil.PartitionTableOnFieldUsingStoredProc(
                //        this.instruction.ConnStr, this.instruction.SchemaName,
                //        this.instruction.TblName, this.instruction.PartitionField,
                //        this.instruction.RecordPerTable, this.instruction.OutputTablePrefix);
                //}
                //else
                //{
                //    DbUtil.PartitionTableOnField(
                //        this.instruction.ConnStr, this.instruction.SchemaName,
                //        this.instruction.TblName, this.instruction.PartitionField,
                //        this.instruction.RecordPerTable, this.instruction.OutputTablePrefix);
                //}
                // keep index
                string[] idxColNames =
                    DbUtil.GetTableIndexedColumnNames(DataProviderType.MSSQL,
                                                      this.instruction.ConnStr,
                                                      this.instruction.SchemaName,
                                                      this.instruction.TblName);
                if(idxColNames !=null && idxColNames.Length>0)
                {
                    for (int i = 1; i <= totalParts; i++)
                    {
                        string partTblName = this.instruction.OutputTablePrefix + i.ToString();
                        foreach (string colName in idxColNames)
                        {
                            string idxName = "IX_" + partTblName + "_" + colName;
                            DbUtil.CreateIndex(
                                DataProviderType.MSSQL,
                                this.instruction.ConnStr,
                                this.instruction.SchemaName,
                                partTblName,
                                colName,
                                idxName);
                        }
                    }
                }

                this.output=new TablePartitionOutput(this.instruction.OwnerComponentID,this._TicketID, totalParts);
                if (this.WorkerFinishedEvent != null)
                    this.WorkerFinishedEvent(this._TicketID, this.GetType(), this.instruction, this.output);
            }
            catch(Exception ex)
            {
                if (this.WorkerErredEvent != null)
                    this.WorkerErredEvent(this._TicketID, this.GetType(), this.instruction, ex.ToString(), true);
            }
        }
        #endregion
    }
}
